﻿using System;
using System.Linq;
using CMS.Services.DTO.User;
using CMS.Services.Models;
using Zinnia.Lite.Repository;
using Zinnia.Lite.Untilty;

namespace CMS.Services.Business.User.Imp
{
    /// <summary>
    /// 用户接口
    /// </summary>
    public partial class UserServices : IUserServices
    {
        private readonly IRepository<UserModel> _useRepository;
        public UserServices(IRepository<UserModel> useRepository)
        {
            _useRepository = useRepository;
        }

        public bool UserNameIsExist(RegisterRequestUserModel model)
        {
            return _useRepository.Table.Any(p => p.UserName == model.UserName);
        }

        public UserModel RegisterUser(RegisterRequestUserModel model)
        {
            if (UserNameIsExist(model))
            {
                throw new Exception($"用户名已经存在：{model.UserName}");
            }
            UserModel userModel = null;
            bool isAdd = false;
            if (string.IsNullOrWhiteSpace(model.Id))
            {
                userModel = new UserModel();
                userModel.UserName = model.UserName;
                userModel.UserPassword = DesEncryptHelper.Instance.Encrypt(model.UserPassword);
                isAdd = true;
            }
            else
            {
                userModel = _useRepository.Get(model.Id);
                if (null == userModel)
                {
                    throw new Exception($"更新注册模型参数有误：{model.Id}");
                }
                if (!string.IsNullOrWhiteSpace(model.UserPassword))
                {
                    userModel.UserPassword = DesEncryptHelper.Instance.Encrypt(model.UserPassword);
                }
            }
            userModel.UserRealName = model.UserRealName;
            userModel.UserAliasName = model.UserAliasName;
            userModel.UserIDCard = model.UserIDCard;
            userModel.UserTel = model.UserTel;
            userModel.UserHomeAddress = model.UserHomeAddress;
            userModel.Province = model.Province;
            userModel.City = model.City;
            userModel.Country = model.Country;
            userModel.Nation = model.Nation;
            userModel.ModifyTime = DateTime.Now;
            if (isAdd)
            {
                _useRepository.Add(userModel);
            }
            else
            {
                _useRepository.Change(userModel);
            }
            _useRepository.Context.SaveChanges();
            return userModel;
        }

        public RegisterReponseUserModel GetRegisterUserModel(RegisterRequestUserModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Id))
                return new RegisterReponseUserModel();
            var userModel = _useRepository.Get(model.Id);
            return (RegisterReponseUserModel)userModel;
        }
    }
}
